package com.tanhua.mogon.api;

import com.tanhua.api.VideoApi;
import com.tanhua.model.mongo.Video;
import com.tanhua.mogon.utils.IdWorker;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    /**
     * 发布视频保存
     * @param video
     * @return
     */
    @Override
    public String saveVideo(Video video) {
        //1.设置属性
        video.setVid(idWorker.getNextId("video"));
        video.setCreated(System.currentTimeMillis());

        //2.保存
        mongoTemplate.save(video);

        return video.getId().toHexString();
    }

    /**
     * 查询小视屏列表（查询缓存中推荐用户id的视频）
     * @param vidList
     * @return
     */
    @Override
    public List<Video> findByVids(List<Long> vidList) {
        List<Video> videoList = mongoTemplate.find(Query.query(
                Criteria.where("vid").in(vidList)
        ), Video.class);
        return videoList;
    }


    /**
     * 查询小视屏列表（分页查询数据库中的）
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Video> findByPage(int page, Integer pagesize) {
        //1.构建查询条件
        Query query = new Query();
        query.skip((page-1)*pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        //2.查询
        List<Video> videoList = mongoTemplate.find(query, Video.class);

        return videoList;
    }
}
